<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8"/>
    <title>论坛 - 云南财经大学信息学院</title>
    <style>
        *{box-sizing:border-box;margin:0;padding:0}
        html,body{height:100%;font-family:"Microsoft YaHei",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif;background:#f8f9fa;color:#333}

        /* 顶部导航栏 - 学院风格 */
        .header{background:linear-gradient(135deg, #003366 0%, #004d99 100%);color:white;padding:15px 30px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 10px rgba(0,0,0,0.1)}
        .header .logo{display:flex;align-items:center;font-size:24px;font-weight:bold}
        .header .logo img{height:40px;margin-right:15px}
        .header .nav{display:flex;gap:30px;font-size:14px}
        .header .nav a{color:white;text-decoration:none;transition:opacity 0.3s}
        .header .nav a:hover{opacity:0.8}
        .header .nav a.active{opacity:0.6;border-bottom:2px solid white;padding-bottom:3px}

        /* 主体容器 */
        .main-container{max-width:1200px;margin:0 auto;padding:30px 20px;min-height:calc(100% - 70px)}

        /* 页面标题 */
        .page-title{text-align:center;margin-bottom:40px;color:#003366}
        .page-title h1{font-size:32px;margin-bottom:10px}
        .page-title .subtitle{color:#6c757d;font-size:16px}

        /* 内容区域 */
        .content-section{background:white;border-radius:12px;box-shadow:0 4px 20px rgba(0,0,0,0.08);padding:30px;margin-bottom:30px}
        .section-title{color:#003366;font-size:22px;margin-bottom:20px;padding-bottom:10px;border-bottom:2px solid #e9ecef}

        /* 论坛主体 - 新样式 */
        .forum-topics{width:100%}
        .topic-item{display:flex;align-items:flex-start;padding:15px;border-bottom:1px solid #e9ecef;transition:background 0.3s}
        .topic-item:hover{background:#f8f9fa}
        .topic-avatar{width:40px;height:40px;border-radius:50%;overflow:hidden;margin-right:15px}
        .topic-avatar img{width:100%;height:100%;object-fit:cover;border-radius:50%}
        .topic-content{flex:1}
        .topic-title{font-weight:500;color:#333;margin-bottom:5px;line-height:1.5;cursor:pointer}
        .topic-title:hover{color:#003366}
        .topic-meta{display:flex;justify-content:space-between;color:#6c757d;font-size:13px;margin-top:10px}
        .topic-author{display:flex;align-items:center}
        .topic-author span{margin-left:5px}
        .topic-stats{display:flex;align-items:center;gap:20px}
        .topic-stats .stat-item{display:flex;align-items:center;cursor:pointer}
        .topic-stats .stat-item i{margin-right:5px}
        .topic-stats .stat-item.liked{color:#ff4757}

        /* 发布主题按钮 */
        .post-btn{display:block;margin:0 auto 30px;background:#003366;color:white;border:none;padding:12px 30px;border-radius:6px;font-size:16px;cursor:pointer;transition:background 0.3s}
        .post-btn:hover{background:#002244}

        /* 分页 */
        .pagination{display:flex;justify-content:center;align-items:center;gap:10px;margin-top:30px}
        .pagination-item{padding:8px 16px;border-radius:4px;cursor:pointer;transition:all 0.3s}
        .pagination-item:hover{background:#e9ecef}
        .pagination-item.active{background:#003366;color:white}
        .pagination-item.disabled{opacity:0.5;cursor:not-allowed}

        /* 模态框样式 */
        .modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:1000;align-items:center;justify-content:center}
        .modal-content{background:white;border-radius:8px;padding:30px;max-width:600px;width:90%;max-height:80vh;overflow-y:auto}
        .modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px}
        .modal-title{font-size:20px;color:#003366}
        .close-btn{background:none;border:none;font-size:24px;cursor:pointer;color:#666}
        .close-btn:hover{color:#000}
        .form-group{margin-bottom:20px}
        .form-group label{display:block;margin-bottom:8px;color:#333}
        .form-group textarea{width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;resize:vertical;min-height:150px}
        .form-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px}
        .btn{padding:8px 20px;border-radius:4px;border:none;cursor:pointer;transition:background 0.3s}
        .btn-primary{background:#003366;color:white}
        .btn-primary:hover{background:#002244}
        .btn-secondary{background:#6c757d;color:white}
        .btn-secondary:hover{background:#5a6268}

        /* 评论区域 */
        .comments-container{margin-top:30px}
        .comments-header{display:flex;justify-content-between;align-items:center;margin-bottom:20px}
        .comment-item{padding:15px 0;border-bottom:1px solid #eee;display:flex;gap:15px}
        .comment-avatar{width:30px;height:30px;border-radius:50%;overflow:hidden}
        .comment-avatar img{width:100%;height:100%;object-fit:cover}
        .comment-content{flex:1}
        .comment-author{font-weight:500;color:#333;margin-bottom:5px}
        .comment-text{color:#666;line-height:1.5}
        .comment-time{font-size:12px;color:#999;margin-top:5px}
        .no-comments{text-align:center;color:#999;padding:40px 0}

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header{padding:10px 15px}
            .header .nav{display:none}
            .topic-avatar{width:30px;height:30px}
            .topic-stats{gap:10px;font-size:12px}
            .modal-content{width:95%;padding:20px}
        }
    </style>
</head>
<body>

<!-- 顶部导航栏 -->
<header class="header">
    <div class="logo">
        <img src="/logo/logo.jpg" alt="院徽">
        <span>云南财经大学信息学院 · 智能校园助手</span>
    </div>
    <nav class="nav">
        <a href="userShow.html">首页</a>
        <a href="forum.html" class="active">论坛</a>
        <a href="about.html">关于我们</a>
        <a href="services.html">服务指南</a>
        <a href="contact.html">联系方式</a>
    </nav>
</header>

<!-- 主体容器 -->
<div class="main-container">
    <div class="page-title">
        <h1>学院论坛</h1>
        <div class="subtitle">师生交流与信息共享平台</div>
    </div>

    <button class="post-btn" id="createPostBtn">发布新主题</button>

    <div class="content-section">
        <h2 class="section-title">最新话题</h2>

        <div class="forum-topics" id="topicsList">
            <!-- 帖子将通过JavaScript动态加载 -->
        </div>

        <!-- 分页 -->
        <div class="pagination" id="pagination">
            <div class="pagination-item" id="prevPage">上一页</div>
            <div class="pagination-item active" id="pageIndicator">第 1 页</div>
            <div class="pagination-item" id="nextPage">下一页</div>
        </div>
    </div>
</div>

<!-- 发布帖子模态框 -->
<div class="modal" id="postModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">发布新主题</h3>
            <button class="close-btn" id="closePostModal">&times;</button>
        </div>
        <div class="form-group">
            <label for="postContent">主题内容</label>
            <textarea id="postContent" placeholder="请输入您想要发布的内容..."></textarea>
        </div>
        <div class="form-actions">
            <button class="btn btn-secondary" id="cancelPostBtn">取消</button>
            <button class="btn btn-primary" id="submitPostBtn">发布</button>
        </div>
    </div>
</div>

<!-- 评论模态框 -->
<div class="modal" id="commentsModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">评论</h3>
            <button class="close-btn" id="closeCommentsModal">&times;</button>
        </div>
        <div id="postDetail">
            <!-- 帖子详情 -->
        </div>
        <div class="comments-container" id="commentsList">
            <!-- 评论将通过JavaScript动态加载 -->
        </div>
        <div class="form-group">
            <textarea id="commentContent" placeholder="写下您的评论..."></textarea>
        </div>
        <div class="form-actions">
            <button class="btn btn-secondary" id="cancelCommentBtn">取消</button>
            <button class="btn btn-primary" id="submitCommentBtn">发表评论</button>
        </div>
    </div>
</div>

<script>
    // DOM 操作辅助函数
    function $(selector) { return document.querySelector(selector); }
    function $$(selector) { return document.querySelectorAll(selector); }

    // 发送 HTTP 请求的通用函数
    async function request(url, options = {}) {
        try {
            const defaultHeaders = {
                'Content-Type': 'application/json'
            };
            const mergedHeaders = { ...defaultHeaders, ...options.headers };
            const mergedOptions = { ...options, headers: mergedHeaders, credentials: 'include' };

            if (mergedOptions.body && typeof mergedOptions.body === 'object') {
                mergedOptions.body = JSON.stringify(mergedOptions.body);
            }

            const res = await fetch(url, mergedOptions);
            if (!res.ok) {
                throw new Error(`请求失败: ${res.status} ${res.statusText}`);
            }

            try {
                return await res.json();
            } catch (e) {
                return res.text();
            }
        } catch (e) {
            console.error('HTTP 请求错误:', e);
            throw e;
        }
    }

    // 论坛相关变量
    let currentPage = 1;
    const pageSize = 10;
    let totalPages = 1;
    let currentPostId = null;
    let currentUserId = '123456'; // 默认值，实际会从API获取
    let currentUserName = '当前用户'; // 默认值，实际会从API获取
    let currentUserAvatar = '/logo/avatar.png'; // 默认值，实际会从API获取

    // 获取当前登录用户信息
    async function getCurrentUserInfo() {
        try {
            const res = await request('/api/user/current');
            if (res.success) {
                currentUserId = res.stuOrTeaId;
                currentUserName = res.nickName;
                currentUserAvatar = res.imageUrl;
            } else {
                console.warn('获取用户信息失败:', res.message);
                // 保持默认值不变
            }
        } catch (e) {
            console.error('获取用户信息请求失败:', e);
            // 保持默认值不变
        }
    }

    // 加载帖子列表
    async function loadPosts() {
        try {
            const res = await request(`/api/forum/posts?page=${currentPage}&pageSize=${pageSize}`);
            const posts = res.posts || [];
            totalPages = Math.max(1, Math.ceil(res.total / pageSize));

            let html = '';
            if (posts.length === 0) {
                html = '<div style="text-align:center;padding:40px 0;color:#999;">暂无帖子</div>';
            } else {
                posts.forEach(post => {
                    html += `
                    <div class="topic-item">
                        <div class="topic-avatar">
                            <img src="${post.imageUrl || '/logo/avatar.png'}" alt="${post.nickName}">
                        </div>
                        <div class="topic-content">
                            <div class="topic-title" onclick="showComments(${post.id}, '${escapeHTML(post.content)}', '${escapeHTML(post.nickName || '未知用户')}', '${post.imageUrl || '/logo/avatar.png'}', '${formatDate(post.createTime)}')">
                                ${escapeHTML(post.content)}
                            </div>
                            <div class="topic-meta">
                                <div class="topic-author">
                                    ${escapeHTML(post.nickName || '未知用户')} | ${formatDate(post.createTime)}
                                </div>
                                <div class="topic-stats">
                                    <div class="stat-item like-btn" data-id="${post.id}">
                                        <i>❤️</i> <span class="like-count">${post.likeCount || 0}</span>
                                    </div>
                                    <div class="stat-item comment-btn" onclick="showComments(${post.id}, '${escapeHTML(post.content)}', '${escapeHTML(post.nickName || '未知用户')}', '${post.imageUrl || '/logo/avatar.png'}', '${formatDate(post.createTime)}')">
                                        <i>💬</i> ${post.commentCount || 0}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    `;
                });
            }

            $('#topicsList').innerHTML = html;
            $('#pageIndicator').textContent = `第 ${currentPage} 页`;

            // 更新分页按钮状态
            $('#prevPage').classList.toggle('disabled', currentPage === 1);
            $('#nextPage').classList.toggle('disabled', currentPage === totalPages);

            // 绑定点赞事件
            bindLikeEvents();

            // 检查每个帖子的点赞状态
            checkLikedStatus();

        } catch (e) {
            console.error('加载帖子失败:', e);
            alert('加载帖子失败：' + e.message);
        }
    }

    // 检查帖子的点赞状态
    async function checkLikedStatus() {
        const likeBtns = $$('.like-btn');
        likeBtns.forEach(btn => {
            const postId = btn.dataset.id;
            checkSingleLikedStatus(postId, btn);
        });
    }

    // 检查单个帖子的点赞状态
    async function checkSingleLikedStatus(postId, btn) {
        try {
            const res = await request(`/api/forum/isLiked?postId=${postId}&stuOrTeaId=${currentUserId}`);
            if (res.liked) {
                btn.classList.add('liked');
            }
        } catch (e) {
            console.error('检查点赞状态失败:', e);
        }
    }

    // 绑定点赞事件
    function bindLikeEvents() {
        const likeBtns = $$('.like-btn');
        likeBtns.forEach(btn => {
            btn.onclick = async function(e) {
                e.stopPropagation(); // 阻止事件冒泡，避免触发查看评论
                const postId = this.dataset.id;
                await toggleLike(postId, this);
            };
        });
    }

    // 切换点赞状态
    async function toggleLike(postId, btn) {
        try {
            const res = await request('/api/forum/like', {
                method: 'POST',
                body: { postId, stuOrTeaId: currentUserId }
            });

            // 更新点赞数和状态
            const likeCount = btn.querySelector('.like-count');
            likeCount.textContent = res.likeCount;

            if (res.liked) {
                btn.classList.add('liked');
            } else {
                btn.classList.remove('liked');
            }

            // 显示操作结果提示
            // alert(res.message); // 移除弹窗提示，提升用户体验
            showStatus(res.message);
        } catch (e) {
            console.error('点赞操作失败:', e);
            alert('点赞操作失败：' + e.message);
        }
    }

    // 显示状态提示
    function showStatus(message) {
        const status = document.createElement('div');
        status.style.position = 'fixed';
        status.style.bottom = '20px';
        status.style.left = '50%';
        status.style.transform = 'translateX(-50%)';
        status.style.backgroundColor = 'rgba(0,51,102,0.9)';
        status.style.color = 'white';
        status.style.padding = '10px 20px';
        status.style.borderRadius = '20px';
        status.style.zIndex = '1000';
        status.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
        status.textContent = message;

        document.body.appendChild(status);

        setTimeout(() => {
            status.style.opacity = '0';
            status.style.transition = 'opacity 0.3s';
            setTimeout(() => {
                document.body.removeChild(status);
            }, 300);
        }, 2000);
    }

    // 显示评论模态框
    function showComments(postId, content, author, avatar, createTime) {
        currentPostId = postId;

        // 填充帖子详情
        const postDetailHtml = `
        <div class="topic-item" style="border-bottom:2px solid #e9ecef;padding-bottom:20px;margin-bottom:20px">
            <div class="topic-avatar">
                <img src="${avatar}" alt="${author}">
            </div>
            <div class="topic-content">
                <div class="topic-title" style="cursor:default">${content}</div>
                <div class="topic-meta">
                    <div class="topic-author">
                        ${author} | ${createTime}
                    </div>
                </div>
            </div>
        </div>
        `;
        $('#postDetail').innerHTML = postDetailHtml;

        // 加载评论
        loadComments(postId);

        // 显示模态框
        $('#commentsModal').style.display = 'flex';
    }

    // 加载评论列表
    async function loadComments(postId) {
        try {
            const res = await request(`/api/forum/comments?postId=${postId}`);
            const comments = res || [];

            let html = '';
            if (comments.length === 0) {
                html = '<div class="no-comments">暂无评论，快来抢沙发吧！</div>';
            } else {
                comments.forEach(item => {
                    const comment = item.comment || item;
                    html += `
                    <div class="comment-item">
                        <div class="comment-avatar">
                            <img src="${item.imageUrl || comment.imageUrl || '/logo/avatar.png'}" alt="${item.nickName || comment.nickName}">
                        </div>
                        <div class="comment-content">
                            <div class="comment-author">${item.nickName || comment.nickName || '未知用户'}</div>
                            <div class="comment-text">${escapeHTML(comment.content || '')}</div>
                            <div class="comment-time">${formatDate(comment.createTime)}</div>
                        </div>
                    </div>
                    `;
                });
            }

            $('#commentsList').innerHTML = html;

        } catch (e) {
            console.error('加载评论失败:', e);
            alert('加载评论失败：' + e.message);
        }
    }

    // 发布帖子
    async function submitPost() {
        const content = $('#postContent').value.trim();
        if (!content) {
            alert('请输入帖子内容');
            return;
        }

        try {
            await request('/api/forum/post', {
                method: 'POST',
                body: { content, stuOrTeaId: currentUserId }
            });

            // 清空输入框并关闭模态框
            $('#postContent').value = '';
            $('#postModal').style.display = 'none';

            // 重新加载帖子列表
            currentPage = 1;
            loadPosts();

            alert('发布成功！');

        } catch (e) {
            console.error('发布帖子失败:', e);
            alert('发布帖子失败：' + e.message);
        }
    }

    // 发布评论
    async function submitComment() {
        const content = $('#commentContent').value.trim();
        if (!content) {
            alert('请输入评论内容');
            return;
        }

        if (!currentPostId) {
            alert('参数错误，请刷新页面重试');
            return;
        }

        try {
            await request('/api/forum/comment', {
                method: 'POST',
                body: {
                    postId: currentPostId,
                    content,
                    stuOrTeaId: currentUserId
                }
            });

            // 清空输入框并重新加载评论
            $('#commentContent').value = '';
            loadComments(currentPostId);

            // 重新加载帖子列表以更新评论数
            loadPosts();

            alert('评论成功！');

        } catch (e) {
            console.error('发布评论失败:', e);
            alert('发布评论失败：' + e.message);
        }
    }

    // 辅助函数：格式化日期 - 显示真实的发表时间
    function formatDate(dateString) {
        if (!dateString) return '未知时间';

        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        // 显示完整的日期和时间：年-月-日 时:分:秒
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 辅助函数：转义HTML特殊字符
    function escapeHTML(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    // 绑定事件
    function bindEvents() {
        // 发布帖子模态框
        $('#createPostBtn').onclick = () => {
            $('#postModal').style.display = 'flex';
        };

        $('#closePostModal').onclick = $('#cancelPostBtn').onclick = () => {
            $('#postModal').style.display = 'none';
        };

        $('#submitPostBtn').onclick = submitPost;

        // 评论模态框
        $('#closeCommentsModal').onclick = $('#cancelCommentBtn').onclick = () => {
            $('#commentsModal').style.display = 'none';
            currentPostId = null;
        };

        $('#submitCommentBtn').onclick = submitComment;

        // 分页
        $('#prevPage').onclick = () => {
            if (currentPage > 1) {
                currentPage--;
                loadPosts();
            }
        };

        $('#nextPage').onclick = () => {
            if (currentPage < totalPages) {
                currentPage++;
                loadPosts();
            }
        };

        // 点击模态框外部关闭
        window.onclick = (event) => {
            if (event.target === $('#postModal')) {
                $('#postModal').style.display = 'none';
            }
            if (event.target === $('#commentsModal')) {
                $('#commentsModal').style.display = 'none';
                currentPostId = null;
            }
        };
    }

    // 页面加载完成后执行
    window.onload = async () => {
        bindEvents();
        await getCurrentUserInfo(); // 先获取当前登录用户信息
        loadPosts();
    };
</script>
</body>
</html>
